import createUploadService from './service/uploda'
import createGzlService from './service/gzl'
import createWebSocketService from './service/websocket'
import { Message } from 'element-ui'
import { applyChain } from './serviceMiddlewareUtil'
import { extendMiddleware, exportMiddleware } from './serviceMiddleware'
import { createFetch, applyMiddleware, methods, filter, headers, log } from '@aev/http'

export const getToken = function () {
  const userInfo = JSON.parse(sessionStorage.getItem('user_info'))
  if (!userInfo) return ''
  return userInfo.token
}

const fetchFactroy = (header) => {
  return createFetch(applyMiddleware(
    methods,
    filter(
      ({ statusCode = 500, message }) => {
        message = message && typeof message === 'string' ? message : '未知错误'
        if (message && message.indexOf('timeout') > -1) {
          message = '请求超时'
        }
        Message.error(message)
      }
    ),
    headers(header)
  ))
}

const urls = {
  gzlUrl: GZL_URL
}
export default vue => {
  const headers = {
    'Authorization': getToken,
    'Content-Type': 'application/json'
  }
  const fetch = fetchFactroy(headers)
  const fetchUpload = fetchFactroy({
    'Authorization': getToken
  })

  const chain = applyChain(vue)
  return {
    gzl: chain([extendMiddleware])(createGzlService(fetch, urls)),
    upload: createUploadService(fetchUpload, urls),
    websocket: createWebSocketService(fetch, urls)
  }
}
